package com.banciyuan.wallpaper.util;

import java.io.File;
import java.math.BigDecimal;

/**
 * Created by hy on 2015/5/4.
 */
public class CacheUtils {
    public static void deleteFilesByDirectory(File directory) {
        try {
            if (directory != null && directory.exists() && directory.isDirectory()) {
                for (File item : directory.listFiles()) {
                    if(item.isFile()){
                        item.delete();
                    }else if(item.isDirectory()){
                        deleteFilesByDirectory(item);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getFormatSize(double size) {
        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "B";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(1, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(1, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(1, BigDecimal.ROUND_HALF_UP)
                    .toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(1, BigDecimal.ROUND_HALF_UP).toPlainString()
                + "TB";
    }

    public static long getFilesSize(File directory) {
        long size = 0;
        try {
            if (directory != null && directory.exists() && directory.isDirectory()) {
                for (File item : directory.listFiles()) {
                    if (item.isDirectory()) {
                        size += getFilesSize(item);
                    } else {
                        size += item.length();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return size;
        }
    }
}
